import AsyncSession from '../services/AsyncSession';
import * as types from '../constants/actionTypes';
import api from '../services/api';
import EasemobChat from '../views/global/EasemobChat';

import {
    AsyncStorage
} from 'react-native';

var KEY_WELCOME_DONE='@global:showwelcome';

function global_init(){
    return async (dispatch)=>{
        //init session 检测是否失效
        let sess = await AsyncSession.init();
        if(sess && sess.user){
            let res = await api.post('/housekeeper/findInfoByT',{t:sess.stoken});

            if(res.cd != "0"){//失效
                dispatch({type:types.CHANGE,
                          session:null});
            }else{
                if(res.data.role == 0 || res.data.role == 2){//业主管家或者物业管家
                    sess.reload = true;
                    dispatch({type:types.CHANGE,
                              session:sess});
                    return;
                }
                
                //判断消息是否登录过
                EasemobChat.isLoggedInBefore((resStr)=>{
                    if(resStr){
                        sess.reload = true;
                        dispatch({type:types.CHANGE,
                                  session:sess});
                    }else{
                        dispatch({type:types.CHANGE,
                                  session:null});
                    }
                });
            }
        }else{//没有登录过
            dispatch({type:types.CHANGE,
                      session:null});
        }

        //init global
        dispatch({type:types.INITIALIZED,
                  welcomedone:!! await AsyncStorage.getItem(KEY_WELCOME_DONE)});
    };
}

function global_welcome_done(){
    return async (dispatch) =>{
        await AsyncStorage.setItem(KEY_WELCOME_DONE, '1');
        dispatch({type:types.WELCOME_DONE});
    };
}

function global_login(){
    return async (dispatch) =>{
        dispatch({type:types.LOGIN_REQUIRED});
    };
}

function global_is_reload(reload){
    return async (dispatch) =>{
        dispatch({type:types.RELOAD_MAIN, reloadmain:reload});
    };
}

function global_is_enter_message(is_enter){
    return async (dispatch) =>{
        dispatch({type:types.IS_ENTER_MESSAGE, is_enter_message:is_enter});
    };
}

function global_reset(){
    AsyncStorage.clear();
}

module.exports = {
    global_init,
    global_welcome_done,
    global_login,
    global_reset,
    global_is_reload,
    global_is_enter_message
};
